package io.renren.service.impl;

import io.renren.service.BaseService;
import io.renren.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import io.renren.dao.CustomContractDao;
import io.renren.entity.CustomContractEntity;
import io.renren.service.CustomContractService;
import org.springframework.transaction.annotation.Transactional;


@Service("customContractService")
public class CustomContractServiceImpl extends BaseService implements CustomContractService {
	@Autowired
	private CustomContractDao customContractDao;
	
	@Override
	public CustomContractEntity queryObject(Integer id){
		return customContractDao.queryObject(id);
	}
	
	@Override
	public List<CustomContractEntity> queryList(Map<String, Object> map){
		return customContractDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return customContractDao.queryTotal(map);
	}
	
	@Override
	public void save(CustomContractEntity customContract){
		customContractDao.save(customContract);
	}
	
	@Override
	public void update(CustomContractEntity customContract){
		customContractDao.update(customContract);
	}
	
	@Override
	public void delete(Integer id){
		customContractDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		customContractDao.deleteBatch(ids);
	}

	@Override
	@Transactional
	public void startSynToB1() throws Exception {
		logger.info("与b1进行数据同步开始");
		Map<String, Object> params = new HashMap<String, Object>();
		String key = Global.getConfig("b1key");// 获取key
		String url = Global.getConfig("b1url5");// 获取url
		logger.info("key:" + key);
		logger.info("url:" + url);

		String sign = Sha1Util.SHA1(params, key);// 计算签名
		logger.info("sign:" + sign);
		params.put("sign", sign);

		String result = HttpClientUtils.doPost(url, params);// 发送请求

		if (result != null) {
			result = result.replace("null", "''");
			Map<String, Object> b1Map = FastJsonUtils.stringToCollect(result);
			if (b1Map != null && b1Map.size() > 0) {
				if (b1Map.get("isSuc") != null && (b1Map.get("isSuc").equals("y"))) {
					logger.info("data"+b1Map.get("data"));
					List<HashMap> dataList = FastJsonUtils.toList(String.valueOf(b1Map.get("data")), HashMap.class);
					//System.out.println("dataList.size:"+dataList.size());
					List<CustomContractEntity> addCustList = new ArrayList();
					if(dataList!=null&&dataList.size()>0){
						List<HashMap> addList = new ArrayList<HashMap>();
						List<HashMap> updateList = new ArrayList<HashMap>();
						List<HashMap> deleteList = new ArrayList<HashMap>();
						List<CustomContractEntity> custList= new ArrayList<CustomContractEntity>();
//						List<DepartmentTree> departmentList= new ArrayList<DepartmentTree>();
						StringBuffer idSb = new StringBuffer();
						String operteType = null;
						String b1Id = null;
						for(HashMap tMap:dataList){
							operteType = tMap.get("operteType").toString();// operteType 1：增加  2：更新  3：删除
							b1Id = tMap.get("conId").toString();
							if("1".equals(operteType)){
								addList.add(tMap);
							}else if("2".equals(operteType)){
								updateList.add(tMap);
							}else if("3".equals(operteType)){
								deleteList.add(tMap);
							}
							idSb.append(b1Id+",");
						}

						if(addList.size()>0){
							for(HashMap aMap:addList){
								CustomContractEntity  custTmp = new CustomContractEntity();
								custTmp.setUnitId(String.valueOf(aMap.get("custId"))); //客户编号
								custTmp.setUnitName(String.valueOf(aMap.get("custName"))); //客户名称
								Date startTime = DateUtils.getDateTimeFormat(String.valueOf(aMap.get("startTime"))); //
								Date endTime = DateUtils.getDateTimeFormat(String.valueOf(aMap.get("endTime")));
								custTmp.setContractBgdate(startTime);
								custTmp.setContractEddate(endTime);
								custTmp.setContractno(String.valueOf(aMap.get("conId")));
								custTmp.setBusinessdesc(String.valueOf(aMap.get("bussDes")));
								custTmp.setCooperationtype(String.valueOf(aMap.get("conType")));
								custTmp.setResponsibilitydepartment(String.valueOf(aMap.get("responDepartment")));
								custTmp.setResponsibilityperson(String.valueOf(aMap.get("responPerson")));
								String totalMoney = String.valueOf(aMap.get("totalMoney"));
								if (totalMoney != null && !"".equals(totalMoney)) {
                                    custTmp.setTotalje(Double.parseDouble(totalMoney));
                                }
//								custTmp.setCooperationunit(); //合作单位
								custTmp.setManagementcosttype(String.valueOf(aMap.get("costType")));
                                String costRate = String.valueOf(aMap.get("costRate"));
                                if ( costRate != null && !"".equals(costRate) ) {
                                    custTmp.setTaxrate(Double.parseDouble(costRate));
                                }
//								String proportionNo = String.valueOf(aMap.get("proportionNo"));
//								if ( proportionNo != null && !"".equals(proportionNo) ) {
									custTmp.setAgreementprice(String.valueOf(aMap.get("proportionNo")));
//								}
								custTmp.setPercentormoney(String.valueOf(aMap.get("proportion").toString()));
								custList.add(custTmp);
							}
							logger.info("批量保存数据开始");
							customContractDao.saveBatch(custList);
							addCustList.addAll(custList);
							logger.info("批量保存数据完成");
						}

						if(updateList.size()>0){
							custList= new ArrayList<CustomContractEntity>();
							for(HashMap aMap:updateList){
								CustomContractEntity custTmp = new CustomContractEntity();
								custTmp.setUnitId(String.valueOf(aMap.get("custId")));
								custTmp.setUnitName(String.valueOf(aMap.get("custName")));
								Date startTime = DateUtils.getDateTimeFormat(String.valueOf(aMap.get("startTime")));
								Date endTime = DateUtils.getDateTimeFormat(String.valueOf(aMap.get("endTime")));
								custTmp.setContractBgdate(startTime);
								custTmp.setContractEddate(endTime);
								custTmp.setContractno(String.valueOf(aMap.get("conId")));
								custTmp.setBusinessdesc(String.valueOf(aMap.get("bussDes")));
								custTmp.setCooperationtype(String.valueOf(aMap.get("conType")));
								custTmp.setResponsibilitydepartment(String.valueOf(aMap.get("responDepartment")));
								custTmp.setResponsibilityperson(String.valueOf(aMap.get("responPerson")));
                                String totalMoney = String.valueOf(aMap.get("totalMoney"));
                                if (totalMoney != null && !"".equals(totalMoney)) {
                                    custTmp.setTotalje(Double.parseDouble(totalMoney));
                                }
//								custTmp.setCooperationunit(); //合作单位
								custTmp.setManagementcosttype(String.valueOf(aMap.get("costType")));
                                String costRate = String.valueOf(aMap.get("costRate"));
                                if ( costRate != null && !"".equals(costRate) ) {
                                    custTmp.setTaxrate(Double.parseDouble(costRate));
                                }
//								String proportionNo = String.valueOf(aMap.get("proportionNo"));
//								if ( proportionNo != null && !"".equals(proportionNo) ) {
									custTmp.setAgreementprice(String.valueOf(aMap.get("proportionNo")));
//								}
								custTmp.setPercentormoney(String.valueOf(aMap.get("proportion").toString()));

								custList.add(custTmp);

							}
							logger.info("批量更新数据开始");
							customContractDao.updateBatch(custList);
							logger.info("批量更新数据完成");
						}

						if(deleteList.size()>0){
							custList= new ArrayList<CustomContractEntity>();
							for(HashMap dMap:deleteList){
								CustomContractEntity  custTmp = new CustomContractEntity();
								custTmp.setContractno(String.valueOf(dMap.get("conId")));
								custList.add(custTmp);
							}
							logger.info("批量删除数据开始");
							customContractDao.deleteBatchByList(custList);
							logger.info("批量删除数据完成");
						}
						/*if(1==1){
							throw new Exception();
						}*/
						//	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

						logger.info("开始更新b1库本次同步的所有记录的状态");
						String urlBack =  Global.getConfig("b1url7");// 获取url，已同步
						Map<String,Object> paramsBack = new HashMap<String,Object>();
						String b1Ids = idSb.toString();
						b1Ids = b1Ids.substring(0,b1Ids.lastIndexOf(","));
						paramsBack.put("conId",b1Ids );
						logger.info("b1Ids:"+b1Ids);
						String signBack = Sha1Util.SHA1(paramsBack, key);// 计算签名
						logger.info("signBack:" + signBack);
						paramsBack.put("sign", signBack);
						logger.info("urlBack:"+urlBack);
						String backResult = HttpClientUtils.doPost(urlBack, paramsBack);// 发送请求
						if (backResult != null) {
							Map<String, Object> b1BackMap = new HashMap<String, Object>();
							b1BackMap = FastJsonUtils.stringToCollect(backResult);
							if (!(b1BackMap.get("isSuc").equals("y"))) {
								if(addCustList.size()>0){
									logger.error("更新b1同步状态失败，删除本地本次新增记录");
									customContractDao.deleteBatchByList(addCustList);
								}
								throw new Exception();
							}
						}else{
							throw new Exception();
						}

						logger.info("同步完成");
					}else{
						logger.info("没有要更新数据，同步完成");
					}
				} else {
					throw new Exception();
				}
			}
		} else {
			throw new Exception();
		}


	}


}
